package com.deram.ctin.tool.zuul.filter;

import com.deram.ctin.common.cache.UserCacheManage;
import com.deram.ctin.common.consts.error.SystemErrorConsts;
import com.deram.ctin.common.utils.JsonUtils;
import com.deram.ctin.common.vo.UserVo;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

/**
 * @author zhangcm
 * @version 1.0, 2017/9/28
 */
@Component
public class WebMemberLoginFilter extends ZuulFilter {

    private final Logger logger = LoggerFactory.getLogger(WebMemberLoginFilter.class);

    @Autowired
    private UserCacheManage userCacheManage;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 100;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext context = RequestContext.getCurrentContext();
        return context.getRequest().getServletPath().startsWith("/rest-web/member/");
    }

    @Override
    public Object run() {
        RequestContext context = RequestContext.getCurrentContext();
        UserVo userVo = userCacheManage.get(context.getRequest());
        if(null == userVo){
            context.setSendZuulResponse(false);
            context.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
            context.setResponseBody(JsonUtils.toJson(SystemErrorConsts.UNLOGIN));
            context.getResponse().setContentType("application/json;charset=UTF-8");
        }
        return null;
    }
}
